import Web3 from 'web3';
import styles from './components.module.less';
import { Button, Typography } from 'antd';
import { observer } from 'mobx-react-lite';

interface WalletConnectProps {
  web3: Web3 | null;
  account: string;
  balance: string;
  networkId: string;
  isConnected: boolean;
  setAccount: (account: string) => void;
  setBalance: (balance: string) => void;
  setNetworkId: (networkId: string) => void;
  setIsConnected: (isConnected: boolean) => void;
}

const WalletConnect = observer(({ web3, account, balance, networkId, isConnected, setAccount, setBalance, setNetworkId, setIsConnected }: WalletConnectProps) => {
  // 连接MetaMask钱包
  const connectWallet = async () => {
    if (!web3) {
      console.log('Web3实例尚未初始化');
      alert('Web3实例尚未初始化，请稍候重试');
      return;
    }

    try {
      // 检查MetaMask是否可用
      if (!(window as any).ethereum) {
        // 提供MetaMask下载链接，而不仅仅是提示
        if (confirm('未检测到MetaMask钱包插件。\n\n是否前往MetaMask官网下载安装？')) {
          window.open('https://metamask.io/download.html', '_blank');
        }
        return;
      }
      
      console.log('尝试连接MetaMask钱包...');
      
      // 检查MetaMask是否已锁定或未连接
      try {
        // 尝试获取当前账户，如果用户已授权过
        const currentAccounts = await (window as any).ethereum.request({
          method: 'eth_accounts'
        });
        console.log('当前已授权账户:', currentAccounts);
      } catch (err) {
        console.log('获取现有账户失败，将请求新授权:', err);
      }
      
      // 请求用户授权连接
      const accounts = await (window as any).ethereum.request({
        method: 'eth_requestAccounts'
      });

      if (accounts && accounts.length > 0) {
        console.log('成功连接到账户:', accounts[0]);
        setAccount(accounts[0]);
        setIsConnected(true);

        try {
          // 获取账户余额
          const balanceWei = await web3.eth.getBalance(accounts[0]);
          const balanceEther = web3.utils.fromWei(balanceWei, 'ether');
          setBalance(balanceEther);
          console.log('成功获取余额:', balanceEther);
        } catch (balanceError) {
          console.error('获取余额失败:', balanceError);
          setBalance('获取失败');
        }

        try {
          // 获取网络ID
          const netId = await web3.eth.net.getId();
          setNetworkId(netId.toString());
          console.log('成功获取网络ID:', netId);
        } catch (networkError) {
          console.error('获取网络ID失败:', networkError);
          setNetworkId('获取失败');
        }
        
        // 更新连接状态
        setIsConnected(true);

        // 监听账户变化
        (window as any).ethereum.on('accountsChanged', (newAccounts: string[]) => {
          console.log('账户发生变化:', newAccounts);
          if (newAccounts.length > 0) {
            setAccount(newAccounts[0]);
            updateBalance(newAccounts[0]);
          } else {
            setAccount('');
            setBalance('0');
            setIsConnected(false);
          }
        });

        // 监听网络变化
        (window as any).ethereum.on('chainChanged', async (newChainId: string) => {
          console.log('网络发生变化:', newChainId);
          setNetworkId(newChainId);
          if (account) {
            await updateBalance(account);
          }
        });
      } else {
        console.log('未获取到账户信息');
        alert('连接失败: 未获取到账户信息');
      }
    } catch (error) {
      console.error('连接钱包失败:', error);
      // 根据不同的错误类型提供更具体的提示
      if ((error as any).code === 4001) {
        // 用户拒绝连接
        alert('连接被取消: 您拒绝了MetaMask的授权请求');
      } else if ((error as any).code === -32002) {
        // MetaMask正在处理请求
        alert('连接请求已发送: 请在MetaMask钱包中确认');
      } else {
        alert('连接钱包失败，请检查MetaMask状态\n\n错误信息: ' + (error as Error).message);
      }
    }
  };

  // 更新账户余额
  const updateBalance = async (accountAddress: string) => {
    if (!web3) return;

    try {
      const balanceWei = await web3.eth.getBalance(accountAddress);
      const balanceEther = web3.utils.fromWei(balanceWei, 'ether');
      setBalance(balanceEther);
    } catch (error) {
      console.error('获取余额失败:', error);
    }
  };

  return (
    <div className={styles.walletConnect}>
      {account === '使用公共节点连接' ? (
        <div className={styles.walletInfo}>
          <Typography.Paragraph><strong>连接方式:</strong> 公共以太坊节点</Typography.Paragraph>
          <Typography.Paragraph><strong>网络:</strong> {networkId}</Typography.Paragraph>
          <Button type="primary" onClick={connectWallet} className={styles.connectButton}>连接MetaMask钱包</Button>
          <Typography.Paragraph className={styles.note}>提示: 连接MetaMask可使用您自己的账户进行交易</Typography.Paragraph>
        </div>
      ) : !isConnected ? (
        <Button type="primary" onClick={connectWallet} className={styles.connectButton}>
          连接MetaMask钱包
        </Button>
      ) : (
        <div className={styles.walletInfo}>
          <Typography.Paragraph><strong>当前账户:</strong> {account}</Typography.Paragraph>
          <Typography.Paragraph><strong>账户余额:</strong> {balance} ETH</Typography.Paragraph>
          <Typography.Paragraph><strong>网络ID:</strong> {networkId}</Typography.Paragraph>
        </div>
      )}
    </div>
  );
});

export default WalletConnect;
